import pymysql
from flask import Flask, request

app = Flask(__name__)

# 数据库连接
db_conn = pymysql.connect(
    host='124.221.242.12', port=8006,
    user='root', password='123456',
    db='test2', charset='utf8',
    autocommit=True,
)

"""
建表SQL
create table user_info
(
    id       int primary key auto_increment,
    name     varchar(32),
    password varchar(32)
);
"""


@app.route('/login/', methods=['GET', 'POST'])
def login():
    """登录"""
    # 拿到post请求中的数据
    user_info = dict(request.form)
    print(user_info)
    # 获取用户名和密码
    username = user_info.get('name')
    password = user_info.get('password')

    # 数据库查询
    login_sql = f"select * from user_info where name = '{username}';"
    cursor = db_conn.cursor()
    affect_rows = cursor.execute(login_sql)

    # 未查询到记录
    if not affect_rows:
        cursor.close()
        return ('当前用户不存在！请先注册！')
    # 查询到记录
    for user in cursor.fetchall():
        if user[2] == password:
            return (f'{username}登录成功！')
    else:
        return ('用户名或密码错误！')


@app.route('/register/', methods=['GET', 'POST'])
def register():
    """注册"""
    # 拿到post请求中的数据
    user_info = dict(request.form)
    print(user_info)
    # 获取用户名和密码
    username = user_info.get('name')
    password = user_info.get('password')

    a = request.files.get('xxx')
    a.save()

    # 数据库添加数据
    register_sql = f"insert into user_info(name,password) values('{username}','{password}');"
    cursor = db_conn.cursor()
    affect_rows = cursor.execute(register_sql)
    cursor.close()

    # 新增成功
    if affect_rows:
        return (f'{username}注册成功！')
    # 新增失败
    return (f'{username}注册失败！')


app.run()
